package com.situ.web.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.situ.web.entity.Student;
import com.situ.web.service.IStudentService;
import com.situ.web.service.impl.StudentServiceImpl;

public class UpdateStudentServlet extends HttpServlet{
	private IStudentService studentService = new StudentServiceImpl();
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		String method = req.getParameter("method");
		if (method.equals("toUpdate")) {
			toUpdate(req, resp);
		} else if (method.equals("update")) {
			update(req, resp);
		}
	}
	private void toUpdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String id = req.getParameter("id");
		Student student = studentService.findById(Integer.parseInt(id));
		req.setAttribute("student", student);
		req.getRequestDispatcher("/student_update.jsp").forward(req, resp);
	}
	
	private void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String id = req.getParameter("id");
		String name = req.getParameter("name");
		String age = req.getParameter("age");
		String gender = req.getParameter("gender");
		Student student = new Student(Integer.parseInt(id), name, Integer.parseInt(age), gender);
		System.out.println(student);
		boolean isSuccess = studentService.updateById(student);
		System.out.println(isSuccess);
		resp.sendRedirect(req.getContextPath() + "/findAllStudent");
	}
}
